package api

import (
	"gateway/basic/config"
	__ "gateway/basic/proto"
	"gateway/consts"
	"gateway/handler/request"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "参数错误",
		})
		return
	}
	_, err := config.DacheClient.Register(c, &__.RegisterReq{
		Username: req.Username,
		Password: req.Password,
		Mobile:   req.Mobile,
		Nickname: req.Nickname,
		SmsCode:  req.SmsCode,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "客户端连接失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "用户注册成功",
	})
}

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "参数错误",
		})
		return
	}
	_, err := config.DacheClient.Login(c, &__.LoginReq{
		Password: req.Password,
		Mobile:   req.Mobile,
		SmsCode:  req.SmsCode,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "客户端连接失败",
		})
		return
	}
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: c.GetUint("userId"),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 3600*24*3,
		},
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "token生成失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "token生成成功",
		"data": token,
	})
}
